"""
-------------------------------------------------
   File Name：     main.py
   Description :
   Author :       willis
   date：          2019/5/27
-------------------------------------------------
   Change Activity:
                   2019/5/27:
                    cycler	0.10.0
                    kiwisolver	1.1.0
                    matplotlib	3.1.0
                    numpy	1.14.6
                    pip	19.0.3
                    pyparsing	2.4.0
                    python-dateutil	2.8.0
                    setuptools	40.8.0
                    six	1.12.0
    将ES平衡结果，每个节点的数量画图
-------------------------------------------------

"""
__author__ = 'willis'

import logging.handlers
import logging
import sys
import os
import numpy
import matplotlib.pyplot as plt
import time

def Log_Out():
    '''
    日志输出
    :return:
    '''

    log_file = os.path.realpath(sys.argv[0]) + '.log'

    # 定义对应的程序模块名name，默认是root
    logs = logging.getLogger()
    logs.setLevel(logging.DEBUG)

    # 定义日志回滚
    logrota = logging.handlers.RotatingFileHandler(log_file, maxBytes=10 * 1024 * 1024, backupCount=20)

    # 设置日志等级
    logrota.setLevel(logging.DEBUG)

    # 日志输出到屏幕控制台
    console = logging.StreamHandler()
    console.setLevel(logging.DEBUG)

    # 定义日志格式
    format = ('%(asctime)s|%(name)s|%(levelname)s|'
              '%(pathname)s|%(lineno)d|%(thread)s|%(process)s|%(message)s')

    # 实例化handler
    formatter = logging.Formatter(format)

    # 格式化handler
    logrota.setFormatter(formatter)
    console.setFormatter(formatter)

    # 添加handler
    logs.addHandler(logrota)
    logs.addHandler(console)

    # logs.debug('my is debug')
    # logs.info('my is info')
    # logs.warning('my is warning')
    # logs.error('my is error')
    # logs.critical('my is critical')
    logs.info('Loging start ...')
    return logs

def mat_hist_bls(action):
    '''
    直方图
    ES平衡前
    :return:
    '''

    # 处理乱码 正常显示中文标签 及正负号
    plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
    plt.rcParams['axes.unicode_minus'] = False

    # 创建一个点数为 8 x 6 的窗口, 并设置分辨率为 80像素/每英寸
    plt.figure(figsize=(8, 6), dpi=80)
    # 创建子图 1 x 1
    plt.subplot(1, 1, 1)

    # 柱子总量
    data_num = 12
    datas = (4, 6, 2, 19, 22, 15, 10, 1, 9, 22, 25, 23)

    # 柱子下标
    index = numpy.arange(data_num)

    # 柱子宽度
    width = 0.35

    # 绘制柱状图，颜色为紫罗兰
    colors = plt.bar(index, datas, width, label='shards', color="#87CEFA")

    # 横轴标签
    plt.xlabel('ES 节点')
    # 坚轴标签
    plt.ylabel('分片数量')

    # 标题
    plt.title('ES 自动平衡结果 /{}'.format(action))

    # 纵横轴刻度
    plt.xticks(index, (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))
    plt.yticks(numpy.arange(0, max(datas), 1))

    # 添加图例
    # plt.legend(loc="upper left")
    plt.legend(loc="best")

    plt.show()

def mat_hist_bls_merge():
    '''
        直方图
        ES平衡前后比对
    :return:
    '''

    # 处理乱码 正常显示中文标签 及正负号
    plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
    plt.rcParams['axes.unicode_minus'] = False

    # 创建一个点数为 8 x 6 的窗口, 并设置分辨率为 80像素/每英寸
    plt.figure(figsize=(8, 6), dpi=80)
    # 创建子图 1 x 1
    plt.subplot(1, 1, 1)

    # 柱子总量 组
    data_groups = 12
    # 柱子数据
    data_before, data_after = data_prod()
    logs.info(data_before)
    logs.info(data_after)

    fig, ax = plt.subplots()

    # 柱子下标
    index = numpy.arange(data_groups)

    # 柱子宽度
    width = 0.35

    opacity = 0.4
    error_config = {'ecolor': '0.3'}

    befores = ax.bar(index, data_before, width, alpha=opacity, color='b', error_kw=error_config, label='before')
    afters = ax.bar(index + width, data_after, width, alpha=opacity, color='r', error_kw=error_config, label='after')

    # 横轴标签
    ax.set_xlabel('ES 节点')
    # 坚轴标签
    ax.set_ylabel('分片数量')

    # 标题
    ax.set_title('ES 自动平衡结果 前后比对图')

    # 纵横轴刻度
    ax.set_xticks(index + width / 2)
    ax.set_xticklabels((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))

    # 添加图例
    ax.legend()

    fig.tight_layout()

    mat_save(plt)

    plt.show()

def mat_save(data):
    '''
    保存文件
    以时间为主
    'es_balance_shards_20190527_000000.jpg'
    支持的文件格式：
    supported formats: eps, pdf, pgf, png, ps, raw, rgba, svg, svgz
    :param data:
    :return:
    '''
    now_date = time.strftime('Y%m%d_%H%M%S', time.localtime())
    file_head = 'es_balance_shards'
    data.savefig("{}_{}.png".format(file_head, now_date))


def data_prod():
    '''
    获取数据
    :return: 平衡前数据元组，平衡后数据元组
    '''

    before = (4, 14, 14, 14, 9, 14, 11, 11, 9, 9, 9, 10)
    after = (10, 11, 10, 11, 11, 10, 11, 11, 11, 11, 10, 11)
    return before, after

if __name__ == '__main__':
    logs = Log_Out()
    # mat_hist_bls('前')
    mat_hist_bls_merge()
